package sales.gz.com.salescounter.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ant.liao.GifView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import sales.gz.com.salescounter.R;
import sales.gz.com.salescounter.bean.ProductsBean;
import sales.gz.com.salescounter.utils.AppContext;
import sales.gz.com.salescounter.utils.N01_Dev_YM;
import sales.gz.com.salescounter.utils.NetworkUtil;

public class MainActivity extends Activity {

    @Bind(R.id.et_number)
    EditText etNumber;
    @Bind(R.id.number1)
    Button number1;
    @Bind(R.id.number2)
    Button number2;
    @Bind(R.id.number3)
    Button number3;
    @Bind(R.id.delete)
    Button delete;
    @Bind(R.id.number4)
    Button number4;
    @Bind(R.id.number5)
    Button number5;
    @Bind(R.id.number6)
    Button number6;
    @Bind(R.id.number0)
    Button number0;
    @Bind(R.id.number7)
    Button number7;
    @Bind(R.id.number8)
    Button number8;
    @Bind(R.id.number9)
    Button number9;
    @Bind(R.id.clear)
    Button clear;
    @Bind(R.id.ly_left)
    LinearLayout lyleft;
    @Bind(R.id.imgbtn)
    ImageView imgbtn;

    private List<ProductsBean> lists;//用户的订单信息
    private AlertDialog dialog;
    private MyAdapter myAdapter;
    private N01_Dev_YM milk_ctrl_dev;
    private List<String> boxs = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        milk_ctrl_dev = new N01_Dev_YM("dev/ttyO2");
        lyleft.setVisibility(View.GONE);
        lists = new ArrayList<ProductsBean>();

        //获取焦点时不弹出软键盘
        etNumber.setOnTouchListener(new View.OnTouchListener(){
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int inType = etNumber.getInputType(); // backup the input type
                etNumber.setInputType(InputType.TYPE_NULL); // disable soft input
                etNumber.onTouchEvent(event); // call native handler
                etNumber.setInputType(inType); // restore input type
                etNumber.setSelection(etNumber.getText().length());
                return true;
            }
        });
        myAdapter = new MyAdapter();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);

    }

    @OnClick({R.id.number1, R.id.number2, R.id.number3, R.id.delete, R.id.number4, R.id.number5, R.id.number6, R.id.number0, R.id.number7, R.id.number8, R.id.number9, R.id.clear,R.id.btn_buy,R.id.btn_get,R.id.ly_left,R.id.imgbtn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.number1:
                String roomInput1 = etNumber.getText().toString();
                etNumber.setText(roomInput1+number1.getText().toString());
                etNumber.setSelection(roomInput1.length()+1);
                break;
            case R.id.number2:
                String roomInput2 = etNumber.getText().toString();
                etNumber.setText(roomInput2+number2.getText().toString());
                etNumber.setSelection(roomInput2.length()+1);
                break;
            case R.id.number3:
                String roomInput3 = etNumber.getText().toString();
                etNumber.setText(roomInput3+number3.getText().toString());
                etNumber.setSelection(roomInput3.length()+1);
                break;
            case R.id.delete:
                String roomIdInput = etNumber.getText().toString();
                if(roomIdInput.length()>0){
                    etNumber.setText(roomIdInput.substring(0,roomIdInput.length()-1));
                    etNumber.setSelection(roomIdInput.length()-1);
                }
                break;
            case R.id.number4:
                String roomInput4 = etNumber.getText().toString();
                etNumber.setText(roomInput4+number4.getText().toString());
                etNumber.setSelection(roomInput4.length()+1);
                break;
            case R.id.number5:
                String roomInput5 = etNumber.getText().toString();
                etNumber.setText(roomInput5+number5.getText().toString());
                etNumber.setSelection(roomInput5.length()+1);
                break;
            case R.id.number6:
                String roomInput6 = etNumber.getText().toString();
                etNumber.setText(roomInput6+number6.getText().toString());
                etNumber.setSelection(roomInput6.length()+1);
                break;
            case R.id.number0:
                String roomInput0 = etNumber.getText().toString();
                etNumber.setText(roomInput0+number0.getText().toString());
                etNumber.setSelection(roomInput0.length()+1);
                break;
            case R.id.number7:
                String roomInput7 = etNumber.getText().toString();
                etNumber.setText(roomInput7+number7.getText().toString());
                etNumber.setSelection(roomInput7.length()+1);
                break;
            case R.id.number8:
                String roomInput8 = etNumber.getText().toString();
                etNumber.setText(roomInput8+number8.getText().toString());
                etNumber.setSelection(roomInput8.length()+1);
                break;
            case R.id.number9:
                String roomInput9 = etNumber.getText().toString();
                etNumber.setText(roomInput9+number9.getText().toString());
                etNumber.setSelection(roomInput9.length()+1);
                break;
            case R.id.clear:
                String roomIdInput1 = etNumber.getText().toString();
                if(roomIdInput1.length()>0){
                    etNumber.setText("");
                }
                break;
            case R.id.btn_buy:
                self_buy_product();
                break;
            case R.id.btn_get:
                get_client_boxno();
                break;
            case R.id.ly_left:

                break;
            case R.id.imgbtn:
                Intent intent = new Intent(MainActivity.this,PassagewayActivity.class);
                startActivity(intent);
                break;


        }
    }
    public void get_client_boxno() {
        if(NetworkUtil.isNetworkConnected(MainActivity.this)){
            createDialog();
            String url = AppContext.baseurl + "api/v2/get_client_boxno";
            RequestParams params = new RequestParams(url);
            params.addParameter("controller_sn", 10000+"");//设备编号GetImei.getphoneimei(MainActivity.this)
            params.addParameter("milk_code", etNumber.getText().toString().trim());//取奶码
            Log.i("aaa", params + "");
            x.http().get(params, new Callback.CommonCallback<String>() {
                @Override
                public void onCancelled(CancelledException arg0) {
                }

                @Override
                public void onError(Throwable arg0, boolean arg1) {
                    Toast.makeText(MainActivity.this,arg0.getMessage(), Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFinished() {
                }

                @Override
                public void onSuccess(String result) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if ("0".equals(jsonObject.getString("ref"))) {
                            dialog.dismiss();
                            lists.clear();
                            lists.addAll(ProductsBean.parse(jsonObject.getJSONArray("result")));
                            Log.i("aaa", lists.size() + "");
                            if (lists.size()>0){
                                createDialog2();
                            }
                        } else{
                            dialog.dismiss();
                            Toast.makeText(MainActivity.this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }else{
            Toast.makeText(MainActivity.this,"抱歉,网络异常",Toast.LENGTH_LONG).show();
        }


    }
    /**
     * 弹框显示用户的订单信息
     */
    private void createDialog2() {
        final AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).create();
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new BitmapDrawable());   // 有白色背景，加这句代码
        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.activity_dialog, null);
        dialog.setCanceledOnTouchOutside(false);//弹出框周围点击不起作用，返回键还起作用
        dialog.setView(view,0,0,0,0);
        dialog.show();
        DisplayMetrics metrics=new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int widthPixels=metrics.widthPixels;
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = widthPixels-40;
        dialog.getWindow().setAttributes(params);


        RecyclerView rcy_build = (RecyclerView) view.findViewById(R.id.recyckerview);
        rcy_build.setLayoutManager(new LinearLayoutManager(MainActivity.this));
        rcy_build.setAdapter(myAdapter);
        myAdapter.notifyDataSetChanged();

        final TextView num = (TextView)view.findViewById(R.id.num);
        for(int i = 0;i<lists.size();i++){
            boxs.add(lists.get(i).getBox_no()+"");
        }

        milk_ctrl_dev.PutStream(boxs);
        /*for (int i = 0;i<lists.size();i++){

            if (i==0){//等于零代表取第一件商品，直接发送请求到售货柜，否则停顿5秒再做请求
                //发送请求都售货柜
                String row = lists.get(i).getBox_no()+"".substring(0,1);
                //milk_ctrl_dev.Start(Integer.parseInt(row),lists.get(i).getBox_no());
                num.setText("请耐心等待......正在为您取第"+i+1+"件商品");
            }else{
                final int number = i+1;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //发送请求到售货柜
                        String row = lists.get(number-1).getBox_no()+"".substring(0,1);
                        //milk_ctrl_dev.Start(Integer.parseInt(row),lists.get(number-1).getBox_no());
                        num.setText("请耐心等待......正在为您取第"+number+"件商品");
                    }
                },5000);
            }

        }*/

    }
    private void createDialog() {
        dialog = new AlertDialog.Builder(MainActivity.this).create();
        Window window = dialog.getWindow();
        //window.setBackgroundDrawable(new BitmapDrawable());   // 有白色背景，加这句代码
        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.input_loading, null);
        dialog.setCanceledOnTouchOutside(false);//弹出框周围点击不起作用，返回键还起作用
        dialog.setView(view,0,0,0,0);
        dialog.show();
        DisplayMetrics metrics=new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int widthPixels=metrics.widthPixels;
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = widthPixels-500;
        params.height = widthPixels-600;
        dialog.getWindow().setAttributes(params);
        GifView gf1 = (GifView) view.findViewById(R.id.gif2);
        // 设置Gif图片源
        gf1.setGifImage(R.mipmap.dynamic);
        // 添加监听器
        // gf1.setOnClickListener(this);
        // 设置显示的大小，拉伸或者压缩
        //gf1.setShowDimension(150, 150);
        // 设置加载方式：先加载后显示、边加载边显示、只显示第一帧再显示
        gf1.setGifImageType(GifView.GifImageType.COVER);
    }

    //房屋适配器
    private class MyAdapter extends RecyclerView.Adapter<MyHolder> {

        @Override
        public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.product_item, parent, false);
            MyHolder myHolder = new MyHolder(view);
            return myHolder;
        }

        @Override
        public void onBindViewHolder(final MyHolder holder, final int position) {
            holder.tx_productname.setText(lists.get(position).getProduct_name());
            holder.tx_num.setText(lists.get(position).getBox_no()==0?"暂时缺货":lists.get(position).getBox_no()+"号格");
        }

        @Override
        public int getItemCount() {
            return lists.size();
        }
    }

    class MyHolder extends RecyclerView.ViewHolder {

        @Bind(R.id.tx_productname)
        TextView tx_productname;
        @Bind(R.id.tx_num)
        TextView tx_num;
        @Bind(R.id.check)
        CheckBox checkBox;

        public MyHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    /**
     * 根据货品码查询商品信息
     */
    public void self_buy_product() {
        if (NetworkUtil.isNetworkConnected(MainActivity.this)){
            createDialog();
            String url = AppContext.baseurl + "api/v2/self_buy_product";
            RequestParams params = new RequestParams(url);
            params.addBodyParameter("controller_sn", 10000+"");//设备编号GetImei.getphoneimei(MainActivity.this)
            params.addBodyParameter("box_no", etNumber.getText().toString().trim());//取奶码
            Log.i("aaa", params + "");
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onCancelled(CancelledException arg0) {
                }

                @Override
                public void onError(Throwable arg0, boolean arg1) {
                    Toast.makeText(MainActivity.this,arg0.getMessage(), Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFinished() {
                }

                @Override
                public void onSuccess(String result) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if ("0".equals(jsonObject.getString("ref"))) {
                            dialog.dismiss();
                            Toast.makeText(MainActivity.this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(MainActivity.this,PayonlineActivity.class);
                            intent.putExtra("sn",jsonObject.getJSONObject("result").getString("sn"));
                            intent.putExtra("product_name",jsonObject.getJSONObject("result").getString("product_name"));
                            intent.putExtra("money",jsonObject.getJSONObject("result").getString("money"));
                            startActivity(intent);
                        } else{
                            dialog.dismiss();
                            Toast.makeText(MainActivity.this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }else{
            Toast.makeText(MainActivity.this,"抱歉,网络异常",Toast.LENGTH_LONG).show();
        }

    }
}
